#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include <QObject>
#include <QTcpSocket>
#include <QJsonObject>

class TcpClient : public QObject
{
    Q_OBJECT
public:
    explicit TcpClient(QObject *parent = nullptr);
    ~TcpClient();

    void connectToServer(const QString& host, quint16 port);
    void sendJson(const QJsonObject& jsonObj);
    void disconnectFromServer();

    QTcpSocket* socket() const { return m_socket; }
    void abortConnection(){m_socket->abort();}


signals:
    // 定义一个信号，当收到服务器的JSON响应时，就发射这个信号
    void serverResponse(const QJsonObject& response);
    void myConnectedToServer();
    void myDisconnectedFromServer();
    void myConnectErrorOccurred(QString message);

private slots:
    // 内部槽函数，用于处理QTcpSocket的信号
    void onReadyRead();
    void onConnected();
    void onDisconnected();
    void onErrorOccurred(QAbstractSocket::SocketError socketError);

private:
    QTcpSocket* m_socket;
    QByteArray m_buffer;      // 缓冲区，用于处理粘包、半包
    qint32     m_packetSize;    // 记录当前包的大小
};

#endif // TCPCLIENT_H
